import { EventEmitter } from 'events'
import crypto from 'crypto'

class Eventer {
  private instance: EventEmitter;
  public emit(eventName: string, eventArgs: any):void {
    const rnd = crypto.randomBytes(6).toString('hex')
    const name = `eventerEx${rnd}`;
    const dataStr = JSON.stringify({ eventName, eventArgs })
    localStorage.setItem(name, dataStr)
    this.instance.emit(eventName, eventArgs)
  }

  public on(eventName, callback): void {
    this.instance.on(eventName, callback)
  }

  private storage(): void {
    const rnd = crypto.randomBytes(6).toString('hex')
    const name = `eventerEx${rnd}`;
    const dataStr = localStorage.getItem(name)
    if (dataStr) {
      const { eventName, eventArgs } = JSON.parse(dataStr)
      this.instance.emit(eventName, eventArgs)
      localStorage.removeItem(name)
    }
    window.addEventListener('storage', (e) => {
      if (e.storageArea != localStorage) return
      if (e.key && !e.key.startsWith('eventerEx')) return
      if (!e.newValue) return
      const dataStr = localStorage.getItem(e.key!);
      const data = JSON.parse(dataStr!)
      this.instance.emit(data.eventName, data.eventArgs)
      localStorage.removeItem(e.key!)
    })
  }

  constructor() {
    this.instance = new EventEmitter()
    this.instance.setMaxListeners(Infinity)
    this.storage()
    console.log("初始化完成")
  }

}

const instance = new Eventer();

export const eventer =  {
  emit(eventName: string, eventArgs: any): void {
    instance.emit(eventName, eventArgs)
  },
  on(eventName, callback): void {
    instance.on(eventName, callback)
  }
}
console.log(eventer['on'])
